<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Controller;
use App\SendLog;
use App\SendOrder;
use App\Support\User as SixUser;
use App\WxUser;
use Illuminate\Http\Request;

class UserController extends Controller {
	protected $model, $sixUser;

	public function __construct(WxUser $user, SixUser $sixUser) {
		$this->model = $user;
		$this->sixUser = $sixUser;
	}

	public function store(Request $request) {
		$this->validate($request, [
			'open_id' => 'required',
			'nick_name' => 'required',
		]);
		$user = $this->model->firstOrCreate(['open_id' => $request->open_id]);
		$user->name = $request->nick_name;
		$user->avatar = $request->image ?: asset('storage/avatars/default.png');
		$user->save();
		return ['code' => 200, 'msg' => 'success', 'data' => $user];
	}

	public function bindPhone(Request $request) {
		$open_id = $request->get('open_id');
		$unique = $request->get('unique');
		if (!$open_id || !$unique) {
			return ['code' => 1, 'msg' => 'missing params'];
		}
		$this->validate($request, [
			'phone' => 'required',
		]);
		$user = $this->model->where('open_id', $open_id)->firstOrFail();

		$user_id = $this->sixUser->register($request->phone);
		if (!$user_id) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$user->six_id = $user_id;
		$user->phone = $request->phone;
		$user->save();
		$send_log = (new SendLog)->where('unique', $unique)->firstOrFail();
		if ($send_log->wx_id != $user->id) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		(new SendOrder)->firstOrCreate([
			'log_id' => $send_log->id,
			'map_id' => $send_log->map_id,
			'order_id' => $send_log->order_id,
			'user_id' => $user_id,
			'phone' => $request->phone,
			'products' => $send_log->products,
		]);
		return ['code' => 0, 'msg' => 'success'];
	}
}
